package service

import (
	"course/basic/config"
	"course/handler/model"
	"course/handler/request"
	"course/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Upload(c *gin.Context) {
	var form request.Upload
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var course model.Course
	if err := course.GetCourse(config.DB, form.CourseName); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "课程不存在",
		})
		return
	}
	file, err := c.FormFile("image")
	if err != nil {
		return
	}
	upload, err := pkg.Upload(file, c)
	if err != nil {
		return
	}
	course.Image = upload
	if err := course.Upload(config.DB); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "上传失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "上传成功",
	})
	return
}
func GetCourse(c *gin.Context) {
	var form request.Upload
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var course model.Course
	if err := course.GetCourse(config.DB, form.CourseName); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "课程不存在",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"course": course,
		},
	})
	return
}
func DelCourse(c *gin.Context) {
	var form request.DelCourse
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}
	var course model.Course
	if err := course.DelCourse(config.DB, form.ID); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "课程删除失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "课程删除成功",
	})
	return
}
